<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CPaymentRequestForm">
          <a-row>
            <a-col :span="12">
              <a-form-item label="付款标题" v-bind="validateInfos.title" id="CPaymentRequestForm-title" name="title">
                <a-input v-model:value="formData.title" placeholder="请输入付款标题" allow-clear></a-input>
              </a-form-item>
            </a-col>
<!--            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentRequestForm-projectId" name="projectId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.projectId"
                  dictCode="c_project_application,project_name,id"
                  placeholder="请选择项目"
                  allow-clear
                />
              </a-form-item>
            </a-col>-->
            <a-col :span="12">
              <a-form-item label="项目" v-bind="validateInfos.projectId" id="CPaymentRequestForm-projectId" name="projectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.projectId"
                  :showSearch="true"
                  :options="projectList"
                  optionFilterProp="label"
                  @change="loadSubProjectList"
                ></a-select>
              </a-form-item>
            </a-col>



            <a-col :span="12" >
              <a-form-item label="子项目" v-bind="validateInfos.subProjectId" id="CPaymentInvoiceForm-subProjectId" name="subProjectId">
                <a-select
                  :disabled="disabledFlag"
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.subProjectId"
                  :showSearch="true"
                  :options="subProjectList"
                  optionFilterProp="label"
                  @change="loadContractorList"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12">
              <a-form-item label="分包商" v-bind="validateInfos.contractorId" id="CPaymentRequestForm-contractorId" name="contractorId">
                <a-select
                  placeholder="请选择"
                  style="width: 100%"
                  v-model:value="formData.contractorId"
                  :showSearch="true"
                  :options="contractorList"
                  optionFilterProp="label"
                ></a-select>
              </a-form-item>
            </a-col>


            <a-col :span="12">
              <a-form-item label="付款总包主体" v-bind="validateInfos.companyId" id="CPaymentRequestForm-companyId" name="companyId">
                 <j-dict-select-tag showSearch="true"
                  v-model:value="formData.companyId"
                  dictCode="c_company_info,company_name,id"
                  placeholder="请选择总包主体"
                  :trigger-change="true"
                  @change="companyChange"
                  allow-clear
                />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="总包主体余额" v-bind="validateInfos.amount" id="CPaymentRequestForm-amount" name="amount">
                <a-input disabled="true" v-model:value="formData.amount" placeholder="请输入总包主体余额" allow-clear></a-input>
              </a-form-item>
            </a-col>



            <a-col :span="12">
              <a-form-item label="申请打款记录" v-bind="validateInfos.applyId" id="CPaymentRequestForm-applyId" name="applyId">
                 <j-dict-select-tag showSearch="true"
                  disabled="true"
                  v-model:value="formData.applyId"
                  dictCode="c_payment_request_apply,apply_title,id"
                  placeholder="请选择子申请打款记录"
                  allow-clear
                />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="发票" v-bind="validateInfos.recordFile" id="CPaymentRequestForm-recordFile" name="recordFile">
                <j-upload v-model:value="formData.recordFile" dragger="true"    :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" ></j-upload>
              </a-form-item>
            </a-col>

          <a-divider>收款银行</a-divider>
            <a-col :span="12">
              <a-form-item label="银行名称" v-bind="validateInfos.bankName" id="CPaymentRequestForm-bankName" name="bankName">
                <a-input v-model:value="formData.bankName" placeholder="请输入银行名称" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="开户行" v-bind="validateInfos.branchName" id="CPaymentRequestForm-branchName" name="branchName">
                <a-input v-model:value="formData.branchName" placeholder="请输入开户行" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行卡号" v-bind="validateInfos.accountNumber" id="CPaymentRequestForm-accountNumber" name="accountNumber">
                <a-input v-model:value="formData.accountNumber" placeholder="请输入银行卡号" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="开户人名称"
                v-bind="validateInfos.accountHolderName"
                id="CPaymentRequestForm-accountHolderName"
                name="accountHolderName"
              >
                <a-input v-model:value="formData.accountHolderName" placeholder="请输入开户人名称" allow-clear></a-input>
              </a-form-item>
            </a-col>

            <a-divider>打款信息</a-divider>
            <a-col :span="12">
              <a-form-item label="本次打款金额" v-bind="validateInfos.paymentAmount" id="CPaymentRequestForm-paymentAmount" name="paymentAmount">
                <a-input-number v-model:value="formData.paymentAmount" placeholder="请输入本次打款金额" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款方式" v-bind="validateInfos.paymentMethods" id="CPaymentRequestForm-paymentMethods" name="paymentMethods">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.paymentMethods" dictCode="payment_methods" placeholder="请选择付款方式" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款凭证" v-bind="validateInfos.paymentAffix" id="CPaymentRequestForm-paymentAffix" name="paymentAffix">
                <j-upload v-model:value="formData.paymentAffix"  dragger="true"  :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }"></j-upload>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款类型" v-bind="validateInfos.paymentType" id="CPaymentRequestForm-paymentType" name="paymentType">
                 <j-dict-select-tag showSearch="true"   v-model:value="formData.paymentType" dictCode="payment_type" placeholder="请选择付款类型" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注" v-bind="validateInfos.remark" id="CPaymentRequestForm-remark" name="remark">
                <a-textarea v-model:value="formData.remark" :rows="4" placeholder="请输入备注" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="打款日期" v-bind="validateInfos.paymentDate" id="CPaymentRequestForm-paymentDate" name="paymentDate">
                <a-date-picker
                  placeholder="请选择打款日期"
                  v-model:value="formData.paymentDate"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-divider>关联收票登记</a-divider>
            </a-col>

            <a-col :span="24">
              <a-form-item label="发票" v-bind="validateInfos.invoiceId" id="CProjectApplicationForm-invoiceId" name="invoiceId">
                <a-select
                  v-model:value="formData.invoiceId"
                  mode="multiple"
                  style="width: 100%"
                  placeholder="请选择发票"
                  :options="invoiceSplitList"
                  @change="handleChange"
                ></a-select>
              </a-form-item>
            </a-col>

            <a-col :span="24">
              <!-- 拆分发票-->

              <a-table :columns="pequestColumns" :data-source="invoiceList" :pagination="false" bordered>
                <template #bodyCell="{ column, text, record }">
                  <template v-if="['splitAmount'].includes(column.dataIndex)"
                    ><!-- 设置编辑的字段-->
                    <div>
                      <a-input v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex]" style="margin: -5px 0" />
                      <template v-else>
                        {{ text }}
                      </template>
                    </div>
                  </template>

                  <template v-else-if="column.dataIndex === 'operation'">
                    <div class="editable-row-operations">
                      <span v-if="editableData[record.id]">
                        <a-typography-link @click="save(record.id)"> <a style="margin-right: 10px">保存</a></a-typography-link>
                        <a-popconfirm title="是否取消？" @confirm="cancel(record.id)">
                          <a>取消</a>
                        </a-popconfirm>
                      </span>
                      <span v-else>
                        <a @click="editPequest(record.id)">编辑</a>
                      </span>
                    </div>
                  </template>
                </template>

                <template #summary>
                  <a-table-summary fixed>
                    <a-table-summary-row>
                      <a-table-summary-cell :index="0">合计</a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                      <a-table-summary-cell :index="1">{{ sumAmount }}</a-table-summary-cell>
                      <a-table-summary-cell :index="1"></a-table-summary-cell>
                    </a-table-summary-row>
                  </a-table-summary>
                </template>
              </a-table>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getLoadinvoiceSplit,getCompanyAmount } from '../CPaymentRequest.api';
  import { columns } from './CPequest.data.ts';
  import type { UnwrapRef } from 'vue';
  import { cloneDeep } from 'lodash-es';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JSelectMultiple from '../../../components/Form/src/jeecg/components/JSelectMultiple.vue';
  import { pequestColumns } from '@/views/paymentrequest/components/CPequest.data.ts';
  import { getCompanyInfoList, getContractorList, getProjectList, getSubProjectList } from '@/views/common.api';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    formBpm: { type: Boolean, default: true },
  });
  const formRef = ref();
  const sumAmount = ref(0);
  const invoiceSplitList = ref();
  const invoiceList = ref();
  const invoiceMap = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const editableData: UnwrapRef<Record<string, DataItem>> = reactive({});
  const formData = reactive<Record<string, any>>({
    id: '',
    projectId: '',
    subProjectId: '',
    contractorId: '',
    paymentDate: '',
    paymentAmount: undefined,
    paymentMethods: '',
    paymentAffix: '',
    paymentType: '',
    remark: '',
    bankName: '',
    branchName: '',
    accountNumber: '',
    accountHolderName: '',
    applyId: '',
    companyId: '',
    amount: '',
    invoiceId: [],
    title: '',
    recordFile:'',
  });
  // const data: DataItem[] = [];
  // const dataSource = ref(data);
  interface DataItem {
    id: string;
    title: string;
    invoiceNumber: string;
    splitAmount: Number;
    totalAmountWithTax: Number;
    highestSplitAmount: Number;
  }

  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    title: [{ required: true, message: '请输入付款款标题!' }],
    // projectId: [{ required: true, message: '请输入项目!' }],
    // subProjectId: [{ required: true, message: '请输入子项目!' }],
    // contractorId: [{ required: true, message: '请输入分包商ID!' }],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(() => {
    if (props.formBpm === true) {
      if (props.formData.disabled === false) {
        return false;
      } else {
        return true;
      }
    }
    return props.formDisabled;
  });

  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  async function edit(record) {
    loadProjectList()
    if(record != undefined ){
      if(record.projectId != undefined &&
        record.projectId != null){
        loadSubProjectList(record.projectId);
      }
      if(record.subProjectId != undefined &&
        record.subProjectId != null){
        loadContractorList(record.subProjectId);
      }
    }

    invoiceList.value = [];
    sumAmount.value = 0;
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if (key === 'invoiceId' && record[key]) {
          tmpData[key] = record[key].split(',');
        } else if (record.hasOwnProperty(key)) {
          tmpData[key] = record[key];
        }
      });
      //赋值
      Object.assign(formData, tmpData);
    });
    const param = {
      projectId: record.projectId,
      subProjectId: record.subProjectId,
      requestId: record.id

    };
    await loadinvoiceSplit(param);
    if (record.id) {
      handleData(record['invoiceId'].split(','));
      companyChange(record.companyId)
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    if(Object.keys(editableData).length > 0){
      createMessage.warning('请先保存所有拆分发票');
      return;
    }
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);

    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }

    model['invoiceList'] = invoiceList.value;
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  //加载 下拉选择数据
  async function loadinvoiceSplit(param) {
    invoiceSplitList.value = [];
    invoiceMap.value = {};
    const rest = await getLoadinvoiceSplit(param);
    for (var i = 0; i < rest.length; i++) {
      const result = rest[i];
      invoiceSplitList.value.push({
        value: result.id,
        label: result.invoiceNumber,
      });

      invoiceMap[result.id] = result;
    }

  }

  /**
   * 总包余额
   * @param value
   */
  async function companyChange(value){
    formData.amount = 0
    if(value){
      const param = {"id":value}
      const rest =await getCompanyAmount(param)
      formData.amount = rest
    }
  }

  //拆分发票
  function editPequest(key) {
    editableData[key] = cloneDeep(invoiceList.value.filter((item) => key === item.id)[0]);
  }
  //拆分发票
  function cancel(key) {
    delete editableData[key];
  }
  //拆分发票
  const save = (key: string) => {
    const invoiceValue = invoiceList.value.filter((item) => key === item.id)[0];
    const editValue = editableData[key];

    let remaining = invoiceValue.totalAmountWithTax-invoiceValue.splitAmountNot-editValue.splitAmount
    remaining = parseFloat(remaining.toFixed(2));

    if (remaining < 0) {
     createMessage.warning('拆分价格大于最大拆分价');
     return;
    }
    invoiceValue.highestSplitAmount = remaining
    editValue.highestSplitAmount = remaining
    editValue.splitAmount =  parseFloat(editValue.splitAmount).toFixed(2)

    Object.assign(invoiceList.value.filter((item) => key === item.id)[0], editableData[key]);
    delete editableData[key];
    sumAmount.value = 0;
    for (var i = 0; i < invoiceList.value.length; i++) {
      const result = invoiceList.value[i];
      //合计
      sumAmount.value += parseFloat(result.splitAmount);
    }
    sumAmount.value = parseFloat(sumAmount.value.toFixed(2));
  };
  function handleChange() {
    handleData(formData.invoiceId);
  }

  function handleData(invoiceIds) {
    sumAmount.value = 0;
    invoiceList.value = [];
    for (var i = 0; i < invoiceIds.length; i++) {
      if(invoiceIds[i] != undefined && invoiceIds[i].length > 0){
        const result2 = invoiceMap[invoiceIds[i]];
        let remaining = result2.totalAmountWithTax-result2.splitAmountNot-result2.splitAmount
        remaining = parseFloat(remaining.toFixed(2));

        invoiceList.value.push({
          id: result2.id,
          title: result2.title,
          invoiceNumber: result2.invoiceNumber,
          totalAmountWithTax: result2.totalAmountWithTax,
          highestSplitAmount: remaining,
          splitAmount: result2.splitAmount,
          splitAmountNot: result2.splitAmountNot,
        });
        //合计
        sumAmount.value += parseFloat(result2.splitAmount);
      }
    }
    sumAmount.value = parseFloat(sumAmount.value.toFixed(2));
  }


  /**
   * 加载 主项目下拉
   */
  const projectList = ref([])
  async function loadProjectList(){
    projectList.value = []
    projectList.value = await getProjectList()
  }
  /**
   * 加载 子主项目 下拉
   */
  const subProjectList = ref([])
  async function loadSubProjectList(projectId){
    formData.subProjectId=undefined
    formData.contractorId=undefined
    contractorList.value = []
    subProjectList.value = []
    const params = {'projectId':projectId}
    subProjectList.value = await getSubProjectList(params)

  }
  /**
   * 加载 分包商
   */
  const contractorList = ref([])
  async function loadContractorList(subProjectId){
    formData.contractorId=undefined
    contractorList.value = []
    const params = {'subProjectId':subProjectId}
    contractorList.value = await getContractorList(params)
  }



  defineExpose({
    add,
    edit,
    submitForm,
    invoiceSplitList,
    loadinvoiceSplit,
    invoiceMap,
    invoiceList,
    editPequest,
    handleChange,
    handleData,
    sumAmount,
    loadSubProjectList,
    loadProjectList,
    loadContractorList,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
